﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using RR;

public partial class Default2 : System.Web.UI.Page
{
    protected RegistRar regrar = new RegistRar();
    HttpCookie _objCookie;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ReadConfig();
            if (_objCookie == null)
            {
                dt1.Date = DateTime.Now.AddDays(-1);
                dt2.Date = DateTime.Now;
            }
            int code = Convert.ToInt32(Request.QueryString["dcod"]);
            if (code > 0)
            {
                LoadDataByCode(code.ToString());
                //grd_OrderDoc.FocusedRowIndex = grd_OrderDoc.FindVisibleIndexByKeyValue(code);
            }
        }
    }

    private void ReadConfig()
    {
        _objCookie = Request.Cookies["oredrDocCookies"];
        if (_objCookie != null)
        {
            if (_objCookie.Values["dt1"] != "") dt1.Date = Convert.ToDateTime(_objCookie.Values["dt1"]);
            if (_objCookie.Values["dt2"] != "") dt2.Date = Convert.ToDateTime(_objCookie.Values["dt2"]);
        }
    }

    private void SaveConfig()
    {
        _objCookie = Request.Cookies["oredrDocCookies"];
        if (_objCookie == null)
        {
            CreateConfig();
        }
        else
        {
            _objCookie.Values["dt1"] = dt1.Text;
            _objCookie.Values["dt2"] = dt2.Text;
            _objCookie.Expires = DateTime.Now.AddDays(5);
            Response.Cookies.Set(_objCookie);
        }
    }

    private void CreateConfig()
    {
        _objCookie = new HttpCookie("oredrDocCookies") { Expires = DateTime.Now.AddDays(20) };
        if (dt1.Text != "") _objCookie["dt1"] = dt1.Text;
        if (dt2.Text != "") _objCookie["dt2"] = dt2.Text;
        Response.Cookies.Add(_objCookie);        
    }

    protected void grd_OrderDoc_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("ORDERDOC_gen");
        if (e.NewValues["STATE"] == null)
            e.NewValues["STATE"] = Convert.ToInt16(0);
        e.NewValues["OPERATOR"] = Profile.UserInfo.ActiveWorker;
    }


    protected void clb1_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        int code = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "CODE"));
        mMenu.Items.FindByName("btn_print").NavigateUrl = String.Format("~/rep/orderRep.aspx?code={0}", code);

        DevExpress.Web.ASPxMenu.MenuItem itm = mMenu.Items.FindByName("btn_column");
        if (e.Parameter != "null")
        {
            switch (Convert.ToInt32(e.Parameter))
            {
                case 0: //не проведен
                    itm.Image.Url = "~/Images/shared/apply.png";
                    itm.ToolTip = "Провести документ";
                    //
                    //  mMenu.Items.FindByName("btn_Delete").Enabled = true;
                    //  mMenu.Items.FindByName("btn_edit").Enabled = true;
                    break;
                case 1: //проведен
                    itm.Image.Url = "~/Images/shared/unapply.png";
                    itm.ToolTip = "Отменить проведение документа";
                    // запрет редактирования
                    //  mMenu.Items.FindByName("btn_Delete").Enabled = false;
                    //  mMenu.Items.FindByName("btn_edit").Enabled = false;
                    break;
            }
           // CompleteDoc(code, Convert.ToInt16(e.Parameter));

        }
    }
    protected void menu_exp_ItemClick(object source, DevExpress.Web.ASPxMenu.MenuItemEventArgs e)
    {

    }

    protected void CompleteDoc(int code, Int16 complete)
    {
        try
        {
            var query = (from d in regrar.ORDERDOC
                         where d.CODE == code
                         select d).First();
            query.STATE = complete;
            regrar.SaveChanges();
        }
        catch (Exception ex)
        {
            throw ex.InnerException;
        }
    }

    protected void clb_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        int code = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "CODE"));

        CompleteDoc(code, Convert.ToInt16(e.Parameter));

    }

    protected void grd_OrderDoc_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
    {
        int state = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "STATE"));
        if (state == 1)
            throw new Exception("Документ проведен. Редактировать запрещено!");
        //grd_OrderDoc_CustomErrorText(grd_OrderDoc,
        //new ASPxGridViewCustomErrorTextEventArgs(GridViewErrorTextKind.General, "Документ проведен. Редактировать запрещено!"));
    }

    protected void grd_OrderDoc_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        int state = Convert.ToInt32(grd_OrderDoc.GetRowValues(grd_OrderDoc.FocusedRowIndex, "STATE"));
        if (state == 1)
            throw new Exception("Документ проведен. Удалять запрещено!");
    }

    //изменяем статус папки
    private void update_Arcplace(int arcplace, Int16 state, bool isSave = true)
    {
        var query = (from a in regrar.ARCPLACE
                     where a.CODE == arcplace
                     select a).First();
        query.STATE = state;
        if (isSave)
            regrar.SaveChanges();
    }
    protected void btn_find_Click(object sender, EventArgs e)
    {
        SaveConfig();
        LoadData();
    }

    private void LoadData()
    {
        if (dt1.Value == null & dt2.Value == null)
        {
            //ReadConfig();
            //if (dt1.Value == null & dt2.Value == null)
            throw new Exception("Укажите период!");
        }
        ds_OrderDoc.Where = "it.DOCUMDATE between @d1 and @d2";
        ds_OrderDoc.WhereParameters.Clear();
        ds_OrderDoc.WhereParameters.Add("d1", DbType.DateTime, dt1.Text);
        ds_OrderDoc.WhereParameters.Add("d2", DbType.DateTime, dt2.Text);
       // grd_OrderDoc.DataSource = ds_OrderDoc;
        grd_OrderDoc.DataBind();
        grd_OrderDoc.FocusedRowIndex = 0;

    }

    private void LoadDataByCode(string code)
    {
        ds_OrderDoc.Where = "it.CODE = @code";
        ds_OrderDoc.WhereParameters.Clear();
        ds_OrderDoc.WhereParameters.Add("code", DbType.Int32, code);
        //grd_OrderDoc.DataSource = ds_OrderDoc;
        grd_OrderDoc.DataBind();
        grd_OrderDoc.FocusedRowIndex = 0;
    }

}